import { ipcMain } from 'electron'
import { dbConnection } from '../database/connection'
import { join } from 'path'
import Database from 'better-sqlite3'

/**
 * 照片相关IPC处理
 */
export function setupPhotoIpc(): void {
  /**
   * 获取照片列表
   */
  ipcMain.handle('photos:getList', (_, { page = 1, limit = 50, orderBy = 'created_at', orderDirection = 'DESC', filters = {} }) => {
    try {
      const db = dbConnection.getConnection()
      const offset = (page - 1) * limit
      
      // 检查是否有照片数据，如果没有则添加一些模拟数据
      const countQuery = 'SELECT COUNT(*) as total FROM photos'
      const countResult = db.prepare(countQuery).get() as { total: number }
      
      if (countResult.total === 0) {
        console.log('数据库中没有照片，添加模拟数据...')
        addMockData(db)
      }
      
      // 构建查询条件
      let whereClause = '1=1'
      const params: any[] = []
      
      if (filters.search) {
        whereClause += ' AND (file_name LIKE ? OR description LIKE ?)'
        params.push(`%${filters.search}%`, `%${filters.search}%`)
      }
      
      if (filters.dateFrom) {
        whereClause += ' AND captured_at >= ?'
        params.push(filters.dateFrom)
      }
      
      if (filters.dateTo) {
        whereClause += ' AND captured_at <= ?'
        params.push(filters.dateTo)
      }
      
      if (filters.cameraMake) {
        whereClause += ' AND camera_make = ?'
        params.push(filters.cameraMake)
      }
      
      if (filters.cameraModel) {
        whereClause += ' AND camera_model = ?'
        params.push(filters.cameraModel)
      }
      
      if (filters.rating !== undefined) {
        whereClause += ' AND rating >= ?'
        params.push(filters.rating)
      }
      
      // 获取总数
      const updatedCountQuery = `SELECT COUNT(*) as total FROM photos WHERE ${whereClause}`
      const updatedCountResult = db.prepare(updatedCountQuery).get(...params) as { total: number }
      
      // 获取照片列表
      const query = `
        SELECT * FROM photos 
        WHERE ${whereClause}
        ORDER BY ${orderBy} ${orderDirection}
        LIMIT ? OFFSET ?
      `
      const photos = db.prepare(query).all(...params, limit, offset)
      
      return {
        success: true,
        data: {
          photos,
          total: updatedCountResult.total,
          page,
          limit,
          totalPages: Math.ceil(updatedCountResult.total / limit)
        }
      }
    } catch (error) {
      console.error('获取照片列表失败:', error)
      return {
        success: false,
        error: '获取照片列表失败'
      }
    }
  })

  /**
   * 获取照片详情
   */
  ipcMain.handle('photos:getById', (_, { id }) => {
    try {
      const db = dbConnection.getConnection()
      const photo = db.prepare('SELECT * FROM photos WHERE id = ?').get(id)
      
      if (!photo) {
        return {
          success: false,
          error: '照片不存在'
        }
      }
      
      return {
        success: true,
        data: photo
      }
    } catch (error) {
      console.error('获取照片详情失败:', error)
      return {
        success: false,
        error: '获取照片详情失败'
      }
    }
  })

  /**
   * 更新照片信息
   */
  ipcMain.handle('photos:update', (_, { id, updates }) => {
    try {
      const db = dbConnection.getConnection()
      
      // 构建更新语句
      const fields = Object.keys(updates).map(key => `${key} = ?`).join(', ')
      const values = Object.values(updates)
      
      const updateQuery = `UPDATE photos SET ${fields}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`
      const result = db.prepare(updateQuery).run(...values, id)
      
      if (result.changes === 0) {
        return {
          success: false,
          error: '照片不存在或更新失败'
        }
      }
      
      return {
        success: true,
        data: { id, ...updates }
      }
    } catch (error) {
      console.error('更新照片失败:', error)
      return {
        success: false,
        error: '更新照片失败'
      }
    }
  })

  /**
   * 删除照片
   */
  ipcMain.handle('photos:delete', (_, { id }) => {
    try {
      const db = dbConnection.getConnection()
      
      // 开始事务
      const transaction = db.transaction(() => {
        // 删除照片标签关联
        db.prepare('DELETE FROM photo_tags WHERE photo_id = ?').run(id)
        
        // 删除照片相册关联
        db.prepare('DELETE FROM photo_albums WHERE photo_id = ?').run(id)
        
        // 删除照片
        const result = db.prepare('DELETE FROM photos WHERE id = ?').run(id)
        
        return result.changes > 0
      })
      
      const success = transaction(id)
      
      if (!success) {
        return {
          success: false,
          error: '照片不存在或删除失败'
        }
      }
      
      return {
        success: true,
        data: { id }
      }
    } catch (error) {
      console.error('删除照片失败:', error)
      return {
        success: false,
        error: '删除照片失败'
      }
    }
  })

  /**
   * 获取照片缩略图路径
   */
  ipcMain.handle('photos:getThumbnail', (_, { id }) => {
    try {
      const db = dbConnection.getConnection()
      const photo = db.prepare('SELECT thumbnail_path FROM photos WHERE id = ?').get(id) as { thumbnail_path: string } | undefined
      
      if (!photo || !photo.thumbnail_path) {
        return {
          success: false,
          error: '缩略图不存在'
        }
      }
      
      return {
        success: true,
        data: photo.thumbnail_path
      }
    } catch (error) {
      console.error('获取缩略图失败:', error)
      return {
        success: false,
        error: '获取缩略图失败'
      }
    }
  })

  /**
   * 批量删除照片
   */
  ipcMain.handle('photos:deleteMultiple', (_, { ids }) => {
    try {
      const db = dbConnection.getConnection()
      
      // 开始事务
      const transaction = db.transaction(() => {
        let deletedCount = 0
        
        for (const id of ids) {
          // 删除照片标签关联
          db.prepare('DELETE FROM photo_tags WHERE photo_id = ?').run(id)
          
          // 删除照片相册关联
          db.prepare('DELETE FROM photo_albums WHERE photo_id = ?').run(id)
          
          // 删除照片
          const result = db.prepare('DELETE FROM photos WHERE id = ?').run(id)
          
          if (result.changes > 0) {
            deletedCount++
          }
        }
        
        return deletedCount
      })
      
      const deletedCount = transaction(ids)
      
      if (deletedCount === 0) {
        return {
          success: false,
          error: '没有照片被删除'
        }
      }
      
      return {
        success: true,
        data: { deletedCount }
      }
    } catch (error) {
      console.error('批量删除照片失败:', error)
      return {
        success: false,
        error: '批量删除照片失败'
      }
    }
  })

  /**
   * 批量更新照片
   */
  ipcMain.handle('photos:updateMultiple', (_, { ids, updates }) => {
    try {
      const db = dbConnection.getConnection()
      
      // 构建更新语句
      const fields = Object.keys(updates).map(key => `${key} = ?`).join(', ')
      const values = Object.values(updates)
      
      const updateQuery = `UPDATE photos SET ${fields}, updated_at = CURRENT_TIMESTAMP WHERE id = ?`
      const update = db.prepare(updateQuery)
      
      // 开始事务
      const transaction = db.transaction(() => {
        let updatedCount = 0
        
        for (const id of ids) {
          const result = update.run(...values, id)
          if (result.changes > 0) {
            updatedCount++
          }
        }
        
        return updatedCount
      })
      
      const updatedCount = transaction(ids)
      
      if (updatedCount === 0) {
        return {
          success: false,
          error: '没有照片被更新'
        }
      }
      
      return {
        success: true,
        data: { updatedCount }
      }
    } catch (error) {
      console.error('批量更新照片失败:', error)
      return {
        success: false,
        error: '批量更新照片失败'
      }
    }
  })
}

/**
 * 添加模拟数据
 * @param db 数据库实例
 */
function addMockData(db: Database.Database): void {
  const mockPhotos = [
    {
      file_path: join(process.cwd(), 'mock-images', 'photo1.jpg'),
      file_name: 'photo1.jpg',
      file_size: 1024000,
      file_hash: 'hash1',
      width: 1920,
      height: 1080,
      format: 'JPEG',
      created_at: new Date('2023-01-15').toISOString(),
      modified_at: new Date('2023-01-15').toISOString(),
      captured_at: new Date('2023-01-15').toISOString(),
      camera_make: 'Canon',
      camera_model: 'EOS 5D Mark IV',
      latitude: 40.7128,
      longitude: -74.0060,
      rating: 5,
      description: '纽约城市风光'
    },
    {
      file_path: join(process.cwd(), 'mock-images', 'photo2.jpg'),
      file_name: 'photo2.jpg',
      file_size: 2048000,
      file_hash: 'hash2',
      width: 3840,
      height: 2160,
      format: 'JPEG',
      created_at: new Date('2023-02-20').toISOString(),
      modified_at: new Date('2023-02-20').toISOString(),
      captured_at: new Date('2023-02-20').toISOString(),
      camera_make: 'Nikon',
      camera_model: 'D850',
      latitude: 34.0522,
      longitude: -118.2437,
      rating: 4,
      description: '洛杉矶日落'
    },
    {
      file_path: join(process.cwd(), 'mock-images', 'photo3.jpg'),
      file_name: 'photo3.jpg',
      file_size: 1536000,
      file_hash: 'hash3',
      width: 2400,
      height: 1600,
      format: 'JPEG',
      created_at: new Date('2023-03-10').toISOString(),
      modified_at: new Date('2023-03-10').toISOString(),
      captured_at: new Date('2023-03-10').toISOString(),
      camera_make: 'Sony',
      camera_model: 'Alpha a7R IV',
      latitude: 37.7749,
      longitude: -122.4194,
      rating: 3,
      description: '旧金山金门大桥'
    },
    {
      file_path: join(process.cwd(), 'mock-images', 'photo4.jpg'),
      file_name: 'photo4.jpg',
      file_size: 3072000,
      file_hash: 'hash4',
      width: 3000,
      height: 2000,
      format: 'JPEG',
      created_at: new Date('2023-04-05').toISOString(),
      modified_at: new Date('2023-04-05').toISOString(),
      captured_at: new Date('2023-04-05').toISOString(),
      camera_make: 'Fujifilm',
      camera_model: 'X-T4',
      latitude: 41.8781,
      longitude: -87.6298,
      rating: 4,
      description: '芝加哥天际线'
    },
    {
      file_path: join(process.cwd(), 'mock-images', 'photo5.jpg'),
      file_name: 'photo5.jpg',
      file_size: 2560000,
      file_hash: 'hash5',
      width: 2560,
      height: 1440,
      format: 'JPEG',
      created_at: new Date('2023-05-12').toISOString(),
      modified_at: new Date('2023-05-12').toISOString(),
      captured_at: new Date('2023-05-12').toISOString(),
      camera_make: 'Canon',
      camera_model: 'EOS R5',
      latitude: 42.3601,
      longitude: -71.0589,
      rating: 5,
      description: '波士顿公园'
    }
  ]

  // 插入模拟数据
  const insertQuery = `
    INSERT INTO photos (
      file_path, file_name, file_size, file_hash, width, height, format,
      created_at, modified_at, captured_at, camera_make, camera_model,
      latitude, longitude, rating, description
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `

  const insert = db.prepare(insertQuery)

  mockPhotos.forEach(photo => {
    insert.run(
      photo.file_path, photo.file_name, photo.file_size, photo.file_hash,
      photo.width, photo.height, photo.format, photo.created_at, photo.modified_at,
      photo.captured_at, photo.camera_make, photo.camera_model,
      photo.latitude, photo.longitude, photo.rating, photo.description
    )
  })

  console.log(`已添加 ${mockPhotos.length} 条模拟照片数据`)
}